package com.ft.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ft.dao.SystemMessageDao;
import com.ft.domain.Message;
import com.ft.domain.Study;
import com.ft.domain.SystemMessage;
import com.ft.service.ISystemService;
import com.ft.utils.ObjectUtils;
import com.ft.websocket.service.ChatEndpoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class SystemServiceImpl extends ServiceImpl<SystemMessageDao, SystemMessage> implements ISystemService {
    @Autowired
    private SystemMessageDao systemMessageDao;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public int addSystemMessage(SystemMessage message) throws IllegalAccessException {
        //先往数据库中存公告
        int i = systemMessageDao.addSystemMessage(message);
        if (i == 1) {
            //1.将帖子id存入缓存
            String id = String.valueOf(message.getId());
            redisTemplate.opsForZSet().add("systemMessageId", id, 1);
            //将帖子信息存入缓存
            String postKey1 = "systemMessage:" + message.getId();
            Map<String, Object> stringObjectMap = ObjectUtils.objectToMap(message);
            redisTemplate.opsForHash().putAll(postKey1, stringObjectMap);
            //同步帖子创建时间
            redisTemplate.opsForHash().delete(postKey1, "createTime");
            String time = systemMessageDao.getcreateTime(message.getId());
            redisTemplate.opsForHash().put(postKey1, "createTime", time);
            //检查是数据否添加成功
            Long hashOrderSize = redisTemplate.opsForHash().size(postKey1);
            while (true) {
                //结束条件,验证每个字段是否都添加上了
                if (hashOrderSize == SystemMessage.total) {
                    break;
                }
                if (hashOrderSize != SystemMessage.total) {
                    //移除key
                    redisTemplate.delete(postKey1);
                    //重新添加
                    Map<String, Object> stringObjectMap1 = ObjectUtils.objectToMap(message);
                    Set mapkey1 = stringObjectMap1.keySet();
                    for (Object key : mapkey1) {
                        redisTemplate.opsForHash().put(postKey1, key, stringObjectMap.get(key));
                    }
                }
            }
            //给当前在线用户推送系统消息
            Message message1 = new Message();
            message1.setIsSystem(0);
            message1.setMessagecontent(JSONObject.toJSONString(message));
            int T = ChatEndpoint.systemMessage(message1);
            if(T == 1){
                return  1 ;
            }else {
                return 0 ;
            }
        } else {
            return i;
        }
    }

    @Override
    public int updateSystemMessage(SystemMessage message) throws IllegalAccessException {
        //先修改数据库
        int i = systemMessageDao.updateSystemMessage(message);
        if (i == 1) {
            //将帖子信息存入缓存
            String postKey1 = "systemMessage:" + message.getId();
            //删除
            redisTemplate.delete(postKey1);
            Map<String, Object> stringObjectMap = ObjectUtils.objectToMap(message);
            redisTemplate.opsForHash().putAll(postKey1, stringObjectMap);
            //同步帖子创建时间
            redisTemplate.opsForHash().delete(postKey1, "createTime");
            String time = systemMessageDao.getcreateTime(message.getId());
            redisTemplate.opsForHash().put(postKey1, "createTime", time);
            return 1;
        }
        return 0;
    }

    /**
     * 逻辑删除公告
     *
     * @param state
     * @param id
     * @return
     */
    @Override
    public int deleteSystemMessage(int state, Long id) {
        int i = systemMessageDao.deleteSystemMessage(state, id);
        if (i == 1) {
            String postKey1 = "systemMessage:" + id;
            redisTemplate.opsForHash().put(postKey1, "state", state);
            return 1;
        }
        return 0;
    }

    /**
     * 获取所有公告
     *
     * @return
     */
    @Override
    public List<SystemMessage> getSystemMessagesList() {
        //返回结果集合
        List result = new ArrayList();
        //获取所有订单数据
        Set buyorderId = redisTemplate.opsForZSet().reverseRangeByScore("systemMessageId", 1, 999);
        //如果数据小于5的情况
        List ids = new ArrayList<>(buyorderId);
        //获取所有数据返回
        for (int i = 0; i < ids.size(); i++) {
            Map entries = redisTemplate.opsForHash().entries("systemMessage:" + ids.get(i));
            //对订单号处理成字符串，防止前端精度丢失
            if((int)entries.get("state") == 0) {
                Object id = entries.get("id");
                entries.put("id", "" + id);
                result.add(entries);
            }
        }
        return result;
    }

}
